﻿using System.Net;
using NAudio.Wave;

namespace TouchFish.Media.Core;

public class NAudioPlay
{
    public void PlayAac(string path )
    {
        // using var member = new MemoryStream();
        // using var media = new StreamMediaFoundationReader(member);
        // using var waveOut = new WaveOutEvent();
        // waveOut.Init(media);
        // waveOut.Play();

        // using var reader = new AudioFileReader(path);
        // using (var waveOut = new WaveOutEvent())
        // {
        //     waveOut.Init(reader);
        //     waveOut.PlaybackStopped += PlayerOnPlaybackStopped;
        //     waveOut.Play();
        // }
        //
        
        // 从网页上播放
        using (Stream ms = new MemoryStream())
        {
            using (Stream stream = WebRequest.Create(path)
                       .GetResponse().GetResponseStream())
            {
                byte[] buffer = new byte[32768];
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
            }

            ms.Position = 0;
            using var media = new StreamMediaFoundationReader(ms);
            using var waveOut = new WaveOutEvent();
            waveOut.Init(media);
            waveOut.PlaybackStopped += PlayerOnPlaybackStopped;
            waveOut.Play();
            while (waveOut.PlaybackState == PlaybackState.Playing )                        
            {
                System.Threading.Thread.Sleep(100);
            }
            // using (WaveStream blockAlignedStream =
            //        new BlockAlignReductionStream(
            //            WaveFormatConversionStream.CreatePcmStream(
            //                new (ms))))
            // {
            //     using (var waveOut = new WaveOutEvent())
            //     {
            //         waveOut.Init(blockAlignedStream);
            //         waveOut.Play();                        
            //         while (waveOut.PlaybackState == PlaybackState.Playing )                        
            //         {
            //             System.Threading.Thread.Sleep(100);
            //         }
            //     }
            // }
        }
    }

    /// <summary>
    /// 播放结束
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <exception cref="NotImplementedException"></exception>
    private void PlayerOnPlaybackStopped(object? sender, StoppedEventArgs e)
    {
      
    }
}